<template>
    <view>
        <view v-if="detail != null">
            <form @submit="formSubmit" class="form-container">
                <view class="form-gorup bg-white oh" v-for="(item, index) in detail.items" :key="index">
                    <view class="oh">
                        <navigator :url="'/pages/fcc/groups/detail/detail?goods_id=' + item.goods_id" hover-class="none">
                            <image class="goods-image fl br" :src="item.images" mode="aspectFill" />
                        </navigator>
						<view class="item-base fl margin-top-sm">
						    <block v-for="(ti, tx) in [1,2,3,4,5]" :key="tx">
						        <image class="xingxing-icon va-m" :src="common_static_url+'stars' + (form_rating_list[index] != undefined && form_rating_list[index] >= ti ? '-active' : '') + '-icon.png'" mode="aspectFill" @tap="rating_event" :data-index="index" :data-value="ti"></image>
						    </block>
						    <text v-if="form_rating_list[index] != undefined" class="cr-grey va-m margin-left-lg">{{rating_msg[form_rating_list[index]-1]}}</text>
						</view>
                    </view>
					<view class="margin-top-main br-t">
					    <textarea @input="form_content_event" :data-index="index" placeholder-class="cr-grey" class="cr-base" :placeholder="lang_info.comment_textarea_placeholder" maxlength="230"></textarea>
					    <view class="form-container-upload oh">
					        <view class="form-upload-data fl">
					            <block v-if="(form_images_list[index] || null) != null && form_images_list[index].length > 0">
					                <view v-for="(ti, ix) in form_images_list[index]" :key="ix" class="item fl">
					                    <text class="delete-icon" @tap="upload_delete_event" :data-index="index" :data-ix="ix">x</text>
					                    <image :src="ti" @tap="upload_show_event" :data-index="index" :data-ix="ix" mode="aspectFill" class="padding-xs dis-block"></image>
					                </view>
					            </block>
					        </view>
					        <image v-if="(form_images_list[index] || null) == null || form_images_list[index].length < 3" class="upload-icon" :src="common_static_url+'upload-icon.png'" mode="aspectFill" @tap="file_upload_event" :data-index="index"></image>
					    </view>
					</view>
                </view>

				<view class="form-gorup anonymous">
				    <switch class="va-m" name="is_anonymous" @change="anonymous_event"></switch>
				    <text class="cr-base va-m">{{lang_info.comment_is_anonymous}}</text>
				    <text class="fr cr-grey margin-top-lg">{{anonymous_msg_list[anonymous_value]}}</text>
				</view>

				<view class="form-gorup form-gorup-submit">
				    <button form-type="submit" class="bg-main br-main cr-white round text-size" type="default" hover-class="none" :disabled="form_button_disabled">{{lang_info.comment_btn_text}}</button>
				</view>
            </form>
        </view>

        <view v-if="detail == null">
            <!-- 提示信息 -->
            <component-no-data :propStatus="data_list_loding_status" :propMsg="data_list_loding_msg"></component-no-data>
        </view>
		<!-- #ifdef APP-PLUS -->
		<yk-authpup ref="authpup" type="top" @changeAuth="changeAuth" :permissionID="permissionID"></yk-authpup>
		<!-- #endif -->
    </view>
</template>

<script>
const app = getApp();
// #ifdef APP-PLUS
import ykAuthpup from "@/components/yk-authpup/yk-authpup";
// #endif
import componentNoData from "@/components/no-data/no-data";
import componentBottomLine from "@/components/bottom-line/bottom-line";
import { groups_base_info } from '@/pages/fcc/groups/public/common.js';
var common_static_url = app.globalData.get_static_url('common');
export default {
	components: {
		// #ifdef APP-PLUS
		ykAuthpup,
		// #endif
	    componentNoData,
	    componentBottomLine
	},
    data() {
        return {
			common_static_url: common_static_url,
            data_list_loding_status: 1,
            data_list_loding_msg: '',
            params: null,
            detail: null,
            editor_path_type: '',
            rating_msg: [],
            anonymous_value: 0,
            anonymous_msg_list: [],
            form_rating_list: [],
            form_images_list: [],
            form_content_list: [],
            form_button_disabled: false,
            undefined: '',
            ix: '',
			permissionID:'',
			peraction:'',
			lang_info:{},
        };
    },
    onLoad(params) {
        //params['id'] = 18;
        this.setData({
            params: params
        });
        this.init();
    },
    onShow() {
        uni.setNavigationBarTitle({
            title: ''
        });
    },
    // 下拉刷新
    onPullDownRefresh() {
        this.init();
    },
    methods: {
		init(){
			groups_base_info()
			.then(data=>{
				this.init_before(data)
				.then(()=>{
					this.init_real()
				});
			});
		},
        // 设置本页参数
        init_before(data){
        	var self = this;
        	return new Promise((resolve, reject) => {
        		self.setData({
        			lang_info:data,
					rating_msg:data.comment_rating_msg_list,
					anonymous_msg_list: data.comment_anonymous_msg_list
        		});
        		uni.setNavigationBarTitle({
        		    title: data.comment_page_title
        		});
        		resolve();
        	});
        },
        // 真正获取数据
        init_real() {
            var self = this;
            uni.showLoading({
                title: this.lang_info.loading_tips
            });
            this.setData({
                data_list_loding_status: 1
            });
            uni.request({
                url: app.globalData.get_request_url('comments', 'index', 'groups'),
                method: 'POST',
                data: {
                    id: this.params.id
                },
                dataType: 'json',
                success: (res) => {
                    console.log(res);
                    uni.hideLoading();
                    uni.stopPullDownRefresh();

                    if (res.data.code == 0) {
                        var data = res.data.data;
                        self.setData({
                            editor_path_type: data.editor_path_type || '',
                            detail: data.data,
                            data_list_loding_status: 3,
                            data_list_loding_msg: ''
                        });
                    } else {
                        self.setData({
                            data_list_loding_status: 2,
                            data_list_loding_msg: res.data.msg
                        });

                        if (app.globalData.is_login_check(res.data, self, 'init_real')) {
                            app.globalData.showToast(res.data.msg);
                        }
                    }
                },
                fail: () => {
                    uni.hideLoading();
                    uni.stopPullDownRefresh();
                    self.setData({
                        data_list_loding_status: 2,
                        data_list_loding_msg: self.lang_info.request_data_error_tips
                    });
                    app.globalData.showToast(self.lang_info.request_data_error_tips);
                }
            });
        },

        // 上传图片预览
        upload_show_event(e) {
            var index = e.currentTarget.dataset.index;
            var ix = e.currentTarget.dataset.ix;
			if(app.globalData.is_android())
			{
				var self = this;
				uni.previewImage({
				    current: self.form_images_list[index][ix],
				    urls: self.form_images_list[index],
					longPressActions: {
						itemList: [self.$t('fengcheche.fcctips.t9')],
						success: function(data) {
							uni.closePreviewImage();
							self.peraction = 'previewImage';
							self.permissionID = 'WRITE_EXTERNAL_STORAGE';
							setTimeout(()=>{
								self.$refs['authpup'].open(self.form_images_list[index][ix]);
							},500);
						},
						fail: function(err) {
							console.log(err.errMsg);
						}
					}
				});
			}else{
				uni.previewImage({
				    current: this.form_images_list[index][ix],
				    urls: this.form_images_list[index]
				});
			}
        },

        // 图片删除
        upload_delete_event(e) {
            var index = e.currentTarget.dataset.index;
            var ix = e.currentTarget.dataset.ix;
            var self = this;
            uni.showModal({
                title: self.lang_info.wenxin_tips_title,
                content: self.lang_info.wenxin_tips_content_delete,
                success(res) {
                    if (res.confirm) {
                        var list = self.form_images_list;
                        list[index].splice(ix, 1);
                        self.setData({
                            form_images_list: list
                        });
                    }
                }
            });
        },

        // 文件上传
		file_upload_event(e) {
			if(app.globalData.is_android())
			{
				this.permissionID = 'CAMERA';
				setTimeout(()=>{
					this.$refs['authpup'].open(e);
				},500);
			}else{
				this.file_upload_event_true(e);
			}
		},
		// #ifdef APP-PLUS
		//用户授权权限后的回调
		changeAuth(e){
			if(this.permissionID == 'WRITE_EXTERNAL_STORAGE')
			{
				if(this.peraction == 'previewImage')
				{
					app.globalData.save_image_by_url(e);
				}else{
					this.file_upload_event_true(e);
				}
			}else{
				// 第一次是摄像头返回，再返回是相册权限，然后才继续执行
				this.peraction = 'fileupload';
				this.permissionID = 'WRITE_EXTERNAL_STORAGE';
				setTimeout(()=>{
					this.$refs['authpup'].open(e);
				},500);
			}
		},
		// #endif
        file_upload_event_true(e) {
            // 数据初始化
            var index = e.currentTarget.dataset.index;
            var temp_list = this.form_images_list;
            var length = this.detail.items.length;

            for (var i = 0; i < length; i++) {
                if (temp_list[i] == undefined) {
                    temp_list[i] = [];
                }
            }

            this.setData({
                form_images_list: temp_list
            }); // 处理上传文件

            var self = this;
            uni.chooseImage({
                count: 3,

                success(res) {
                    var success = 0;
                    var fail = 0;
                    var length = res.tempFilePaths.length;
                    var count = 0;
                    self.upload_one_by_one(index, res.tempFilePaths, success, fail, count, length);
                }
            });
        },

        // 采用递归的方式上传多张
        upload_one_by_one(index, img_paths, success, fail, count, length) {
            var self = this;

            if ((self.form_images_list[index] || null) == null || self.form_images_list[index].length < 3) {
                uni.uploadFile({
                    url: app.globalData.get_request_url('index', 'ueditor'),
                    filePath: img_paths[count],
                    name: 'upfile',
                    formData: {
                        action: 'uploadimage',
                        path_type: self.editor_path_type
                    },
                    success: function (res) {
                        success++;

                        if (res.statusCode == 200) {
                            var data = typeof res.data == 'object' ? res.data : JSON.parse(res.data);

                            if (data.code == 0 && (data.data.url || null) != null) {
                                var list = self.form_images_list;

                                if ((list[index] || null) == null) {
                                    list[index] = [];
                                }

                                list[index].push(data.data.url);
                                self.setData({
                                    form_images_list: list
                                });
                            } else {
                                app.globalData.showToast(data.msg);
                            }
                        }
                    },
                    fail: function (e) {
                        fail++;
                    },
                    complete: function (e) {
                        count++; // 下一张

                        if (count >= length) {
                            // 上传完毕，作一下提示
                            //app.showToast('上传成功' + success +'张', 'success');
                        } else {
                            // 递归调用，上传下一张
                            self.upload_one_by_one(index, img_paths, success, fail, count, length);
                        }
                    }
                });
            }
        },

        // 是否匿名事件
        anonymous_event(e) {
            this.setData({
                anonymous_value: e.detail.value == true ? 1 : 0
            });
        },

        // 评分事件
        rating_event(e) {
            // 参数
            var index = e.currentTarget.dataset.index;
            var value = e.currentTarget.dataset.value; // 数据初始化/赋值

            var temp_list = this.form_rating_list;
            var length = this.detail.items.length;

            for (var i = 0; i < length; i++) {
                if (temp_list[i] == undefined) {
                    temp_list[i] = 0;
                }

                if (index == i) {
                    temp_list[i] = value;
                }
            }

            this.setData({
                form_rating_list: temp_list
            });
        },

        // 评论内容
        form_content_event(e) {
            // 参数
            var index = e.currentTarget.dataset.index;
            var value = e.detail.value; // 数据初始化/赋值

            var temp_list = this.form_content_list;
            var length = this.detail.items.length;

            for (var i = 0; i < length; i++) {
                if (temp_list[i] == undefined) {
                    temp_list[i] = '';
                }

                if (index == i) {
                    temp_list[i] = value;
                }
            }

            this.setData({
                form_content_list: temp_list
            });
        },

        // 表单
        formSubmit(e) {
            // 商品数量
            var length = this.detail.items.length; 
			
			// 评分校验
            var count = this.form_rating_list.length;

            if (count < length) {
                app.globalData.showToast(this.lang_info.comment_tips_please_score);
                return false;
            }

            var max = Math.max.apply(null, this.form_rating_list);
            var min = Math.min.apply(null, this.form_rating_list);

            if (min < 1 || max > 5) {
                app.globalData.showToast(this.lang_info.comment_tips_wrong_score);
                return false;
            } 
			
			// 内容校验
            var count = this.form_content_list.length;
            if (count < length) {
                app.globalData.showToast(this.lang_info.comment_tips_empty_content);
                return false;
            }

            for (var i in this.form_content_list) {
                var count = this.form_content_list[i].length;

                if (count < 6 || count > 230) {
                    app.globalData.showToast(this.lang_info.comment_tips_content_length);
                    return false;
                }
            } 
			
			// 图片校验
            if (this.form_images_list.length > 0) {
                for (var i in this.form_images_list) {
                    if (this.form_images_list[i].length > 3) {
                        app.globalData.showToast(this.lang_info.comment_tips_images_length);
                        return false;
                    }
                }
            } 
			
			// 表单数据
            var form_data = e.detail.value;

            if (form_data['is_anonymous'] == true) {
                form_data['is_anonymous'] = 1;
            } else {
                form_data['is_anonymous'] = 0;
            }

            form_data['id'] = this.detail.id;
            form_data['goods_id'] = JSON.stringify(
                this.detail.items.map(function (v) {
                    return v.goods_id;
                })
            );
            form_data['rating'] = JSON.stringify(this.form_rating_list);
            form_data['content'] = JSON.stringify(this.form_content_list);

            if (this.form_images_list.length > 0) {
                form_data['images'] = JSON.stringify(this.form_images_list);
            } else {
                form_data['images'] = '';
            } 
			
			// 提交表单
            var self = this;
            uni.showLoading({
                title: this.lang_info.loading_process_tips
            });
            self.setData({
                form_button_disabled: true
            });
            uni.request({
                url: app.globalData.get_request_url('commentssave', 'index', 'groups'),
                method: 'POST',
                data: form_data,
                dataType: 'json',
                header: {
                    'content-type': 'application/x-www-form-urlencoded'
                },
                success: (res) => {
                    console.log(res);
                    uni.hideLoading();

                    if (res.data.code == 0) {
                        app.globalData.showToast(res.data.msg, 'success');
                        setTimeout(function () {
                            uni.navigateBack();
                        }, 2000);
                    } else {
                        self.setData({
                            form_button_disabled: false
                        });
                        app.globalData.showToast(res.data.msg);
                    }
                },
                fail: () => {
                    uni.hideLoading();
                    self.setData({
                        form_button_disabled: false
                    });
                    app.globalData.showToast(self.lang_info.request_data_error_tips);
                }
            });
        }
    }
};
</script>
<style>
@import './comment.css';
</style>
